import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common'

import { Response, Request } from 'express'

/**
 * 拦截过滤器封装
 */
@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp() // 获取请求上下文
    const req = ctx.getRequest<Request>() // 获取请求对象
    const res = ctx.getResponse<Response>() // 获取响应对象
    const status = exception.getStatus() // 获取异常状态码
    res.status(status).json({
      success: false,
      time: new Date().toLocaleString(),
      data: { message: exception.message },
      status,
      path: req.url,
    })
  }
}
